package cn.bellychang.leetcode.question102;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author ChangLiang
 * @date 2021/3/15
 */
public class Solution3 {

    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> result = new ArrayList<>();

        if (root == null) {
            return result;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        // 当前层有多少个
        int currentLevelSize = 1;

        // 下一层有多少个
        int nextLevelSize = 0;

        // 当前层已经loop的个数
        int currentSize = 0;

        List<Integer> list = new ArrayList<>();

        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            list.add(node.val);

            currentSize++;
            if (node.left != null) {
                queue.add(node.left);
                nextLevelSize++;
            }
            if (node.right != null) {
                queue.add(node.right);
                nextLevelSize++;
            }
            if (currentSize >= currentLevelSize) {
                currentLevelSize = nextLevelSize;
                nextLevelSize = 0;
                currentSize = 0;
                result.add(list);
                list = new ArrayList<>();
            }
        }

        return result;
    }
}
